package com.leesche.zcsp.node.web.intecepter.wechat;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.leesche.zcsp.node.web.controller.wechat.login.WechatLoginController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.leesche.zcsp.node.pay.wecha.service.WechatService;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.service.privilege.PrivilegeService;
import com.leesche.zcsp.node.web.vo.Principal;

/**
 * 
 * @Title: WeixinLoginVerifyInterceptor.java
 * @Description: TODO(验证当前是否登录)
 * @author Jerry Chen
 * @date 2016年10月24日 下午2:45:06
 * @version V1.0
 */
public class WechatLoginVerifyInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	PrivilegeService privilegeService;

	@Autowired
	WechatService wechatService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		Principal principal = privilegeService.getCurrentPrincipal();

		if (principal == null) {
			String requestType = request.getHeader("X-Requested-With");
			if ((requestType != null)
					&& (requestType.equalsIgnoreCase("XMLHttpRequest"))) {
				response.addHeader("status", "accessDenied");
				response.sendError(403);
				return false;
			} else {
				String redirectUrl = request.getScheme() + "://"
						+ request.getServerName() + request.getRequestURI();
				if (StringUtils.isNotBlank(request.getQueryString())) {
					redirectUrl = redirectUrl + "?" + request.getQueryString();
				}

				StringBuffer url = new StringBuffer();

				url.append(request.getScheme());
				url.append("://");
				url.append(request.getServerName());
				url.append("/");
				url.append(Constants.SITE_NAME);

				url.append(WechatLoginController.CURRENT_SITENAME);
				url.append("gotoSignIn");
				url.append("?redirectUrl=" + URLEncoder.encode(redirectUrl));

				response.sendRedirect(wechatService.getWechatRedirectUrl(url
						.toString()));
				return false;
			}
		}

		return true;
	}

}
